<?php
/**
 * Admin Groups Controller
 *
 * This handles all AJAX requests from the Admin GUI Group page.
 * These methods will create an AJAX response containing JSON data. The JSON
 * data is read by the JS code and rendered into interface.
 *
 * @access 	public
 * @author 	Valentin
 * @copyright	ResMania 2009 all rights reserved.
 * @link		http://developer.resmania.com/api
 */
class RM_Admin_Groups_EditController extends RM_Controller
{
    function editJsonAction()
    {
        $id = $this->_getParam('id');
        $iso = $this->_getParam('iso');

        $model = new RM_Groups();
        $row = $model->find($id)->current();
        $data = $row->toArray();
        $data['name'] = $data[$iso];
        $data['main_unit_name'] = $row->getUnit($iso)->name;
        unset($data[$iso]);

        return array(
            'data' => $data
        );
    }

    function updateJsonAction()
    {
        $data = $this->_getParam('edit_group');
        $iso = $this->_getParam('iso');
        $data[$iso] = $data['name'];
        unset($data['name']);

        $model = new RM_Groups();
        $row = $model->find($data['id'])->current();
        unset($data['id']);
        foreach ($data as $key => $value) {
            $row->$key = $value;
        }
        $row->save();

        $unitModel = new RM_Units();
        $unit = $unitModel->find($row->main_unit_id)->current();
        if ($unit !== null) {
            $unit->group_id = $row->id;
        }
        $unit->save();

        return array(
            'data' => array('success' => true)
        );
    }

    /**
     * Ajax action method to delete groups
     *
     * @param ids - array from request with ids of groupds that need to be deleted
     * @return stdClass object
     */
    public function deleteJsonAction()
    {
        $id = $this->_getParam('id');

        $model = new RM_Groups();
        $row = $model->find($id)->current();
        $row->delete();

        return array(
            'data' => array('success' => true)
        );
    }
}